package com.ftwj.demo.message.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ftwj.demo.base.wrapper.ConditionWrapper;
import com.ftwj.demo.message.SendInterface;
import com.ftwj.demo.modular.dao.NoticeDao;
import com.ftwj.demo.modular.dao.NoticeFileDao;
import com.ftwj.demo.modular.dao.NoticeUserDao;
import com.ftwj.demo.modular.entity.NoticeBean;
import com.ftwj.demo.modular.entity.NoticeFileBean;
import com.ftwj.demo.modular.entity.NoticeUserBean;
import com.ftwj.demo.global.shiro.ShiroUtil;

@Component
public class NoticeSend implements SendInterface<NoticeBean> {
	
	@Autowired
	private NoticeDao noticeDao;
	@Autowired
	private NoticeUserDao userDao;
	@Autowired
	private NoticeFileDao fileDao;

	/**
	 * <p>Title: send</p>  
	 * <p>Description: 公告发送</p>  
	 * @param bean
	 * @author HeYang
	 * @date 2020年4月9日  
	 * @version 1.0
	 */
	@Override
	public Integer send(NoticeBean bean) {
		Integer user = ShiroUtil.getUserId();	
		List<Integer> userList = bean.getUserIdList();
		List<String> fileList = bean.getFiles();	
		Integer noticeId = bean.getNoticeId();
		if(null==noticeId) {
			//新增
			bean.setCreateUser(user).setCreateTime(new Date()).setState(1);
			noticeId = noticeDao.insertAndGetId(bean);
		}else {
			//修改
			noticeDao.update(bean);
		}
		if(userList != null && !userList.isEmpty()) {
			ConditionWrapper wrapper=new ConditionWrapper();
			wrapper.eq("notice_id", noticeId);
			userDao.deleteByConditions(wrapper);
			for (Integer userId : userList) {
				NoticeUserBean noticeUser = new NoticeUserBean();
				noticeUser.setNoticeId(noticeId).setUserId(userId).setState(0);
				userDao.insert(noticeUser);
			}
		}
		if(fileList != null && !fileList.isEmpty()) {
			ConditionWrapper wrapper=new ConditionWrapper();
			wrapper.eq("notice_id", noticeId);
			fileDao.deleteByConditions(wrapper);
			for (String fileId : fileList) {
				NoticeFileBean noticeFile = new NoticeFileBean();
				noticeFile.setNoticeId(noticeId).setFileId(fileId).setCreateUser(user).setCreateTime(new Date());
				fileDao.insert(noticeFile);
			}
		}
		return 0;
	}

}
